package com.it.interceptors;

import com.it.utils.JwtUtil;
import com.it.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        String requestURI = request.getRequestURI(); // 获取请求路径
        String requestMethod = request.getMethod(); // 获取请求方法

        try {
            // 1. 校验 Token 有效性（原有逻辑）
            if (token == null || token.trim().isEmpty()) {
                throw new Exception("Token 为空");
            }

            String redisToken = stringRedisTemplate.opsForValue().get(token);
            if (redisToken == null) {
                throw new Exception("Token 无效或已过期");
            }

            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);

            // 2. 权限校验：仅对 /books 路径下的增删改操作校验角色（role=1）
            if (isBooksModifyRequest(requestURI, requestMethod)) {
                Integer role = (Integer) claims.get("role");
                if (role == null || role != 1) { // role=1 为管理员
                    response.setStatus(403); // 权限拒绝
                    return false;
                }
            }

            return true;
        } catch (Exception e) {
            System.err.println("验证失败原因: " + e.getMessage());
            response.setStatus(401); // 未认证或权限不足
            return false;
        }
    }

    // 判断是否为 /books 路径下的增删改请求
    private boolean isBooksModifyRequest(String requestURI, String requestMethod) {
        // 路径以 /books 开头
        boolean isBooksPath = requestURI.startsWith("/books");
        // 请求方法为 POST/PUT/DELETE（增删改）
        boolean isModifyMethod = requestMethod.equals("POST") || requestMethod.equals("PUT") || requestMethod.equals("DELETE");
        return isBooksPath && isModifyMethod;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadLocalUtil.remove();
    }
}